package com.xuxingcan;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

/**
 * Created by xuxingcan on 2/22/16.
 */
public class FileUtil {
    private static int BUFFER_SIZE = 1024;

    /**
     * 下载指定文件
     *
     * @param downloadUrl
     * @param file
     * @throws Exception
     */
    public static void downloadFile(String downloadUrl, File file) throws Exception {
        URLConnection conn = new URL(downloadUrl).openConnection();
//        if (file.exists()) {
//            int fileSize = conn.getContentLength();
//            if (file.length() == fileSize) {
//                System.out.println(file.getName() + " is alread downloaded!");
//                return;
//            } else {
//                file.delete();
//            }
//        }
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        byte[] buf = new byte[BUFFER_SIZE];
        int len = -1;
//        System.out.println(new Date().toString() + " : " + file.getName() + " is downloading......");
        FileOutputStream out = new FileOutputStream(file);
        while (true) {
            len = bis.read(buf, 0, BUFFER_SIZE);
            if (len == -1) {
                break;
            }
            out.write(buf, 0, len);
            out.flush();
        }
        out.close();
    }

    /**
     * 下载文件至指定文件夹
     *
     * @param downloadUrl
     * @param file
     * @throws Exception
     */
    public static void downloadFile(String downloadUrl, File file, String fileName) throws Exception {
        if (file.isDirectory()) {
            downloadFile(downloadUrl, new File(file, fileName));
        } else {
            downloadFile(downloadUrl, file);
        }
    }
}
